package com.lizhiyu.flink.monitor;

import com.lizhiyu.flink.model.AccessLogDO;
import com.lizhiyu.flink.model.ResultCount;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

/**
 * 每30秒统计，过去1分钟，各个接口的各个状态码次数，1分钟内超过5次则告警
 * 也就是监控系统
 */
public class AlarmTest {

    public static void main(String[] args) throws Exception {
        //构建执行任务环境以及任务的启动的入口, 存储全局相关的参数
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //java,2022-11-11 09-10-10,15
        DataStream<AccessLogDO> ds =  env.addSource(new AccessLogSource());


        //过滤一些没有的url
        SingleOutputStreamOperator<AccessLogDO> filterDS = ds.filter(new FilterFunction<AccessLogDO>() {
            @Override
            public boolean filter(AccessLogDO value) throws Exception {
                return StringUtils.isNotBlank(value.getUrl());
            }
        });


        //指定watermark
        SingleOutputStreamOperator<AccessLogDO> watermarkDS = filterDS.assignTimestampsAndWatermarks(WatermarkStrategy
                //根据时间戳排序 (这个兜底策略是什么样 ?)
                .<AccessLogDO>forMonotonousTimestamps()
                //指定POJO事件时间列，毫秒
                .withTimestampAssigner((event, timestamp) -> event.getCreateTime().getTime()));

        //最后的兜底数据
        OutputTag<AccessLogDO> lateData = new OutputTag<AccessLogDO>("lateDataLog"){};

        //多个字段分组
        KeyedStream<AccessLogDO, Tuple2<String, Integer>> keyedStream = watermarkDS.keyBy(new KeySelector<AccessLogDO, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> getKey(AccessLogDO value) throws Exception {
                return Tuple2.of(value.getUrl(),value.getHttpCode());
            }
        });

//        WindowedStream<AccessLogDO, Tuple2<String, Integer>, TimeWindow> windowDS = keyedStream
//                //开窗，滑动窗口，每30秒统计近60秒的访问量
//                .window(SlidingEventTimeWindows.of(Time.seconds(60), Time.seconds(30)))
//                //允许1分钟延迟
//                .allowedLateness(Time.minutes(1))
//                //设置侧输出流
//                .sideOutputLateData(lateData);

        Pattern<AccessLogDO, AccessLogDO> pattern = Pattern.<AccessLogDO>begin("errorCode")
                .where(new SimpleCondition<AccessLogDO>() {
                    @Override
                    public boolean filter(AccessLogDO value) throws Exception {
                        // 状态码
                        return value.getHttpCode() != 200;
                    }
                    //30秒出现3次
                }).timesOrMore(3).within(Time.seconds(30));

        //匹配检查
        PatternStream<AccessLogDO> patternStream = CEP.pattern(keyedStream, pattern);
        //获得匹配成功的结果
        SingleOutputStreamOperator<ResultCount> cepDs = patternStream.select(new PatternSelectFunction<AccessLogDO, ResultCount>() {
            @Override
            public ResultCount select(Map<String, List<AccessLogDO>> map) throws Exception {
                List<AccessLogDO> errorCode = map.get("errorCode");
                AccessLogDO accessLogDO = errorCode.get(0);
                ResultCount resultCount = new ResultCount();
                resultCount.setUrl(accessLogDO.getTitle());
                resultCount.setCount(Long.valueOf(errorCode.size()));
                resultCount.setHttpCode(accessLogDO.getHttpCode());
                return resultCount;
            }
        });
        cepDs.print("alarm:");
        env.execute();
    }
}

